package com.mdp.tpa.pay.cm.service;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.google.gson.Gson;
import com.mdp.core.api.CacheHKVService;
import com.mdp.tpa.pay.alipay.service.AlipayService;
import com.mdp.tpa.pay.cm.client.AcClient;
import com.mdp.tpa.pay.cm.entity.Orders;
import com.mdp.tpa.pay.cm.entity.PaymentSeq;
import com.mdp.tpa.pay.wxpay.enums.WxTradeState;
import com.mdp.tpa.pay.wxpay.service.WxpayNativeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderAutoService {



    private Logger log= LoggerFactory.getLogger(WxpayNativeService.class);

    @Autowired
    AcClient acClient;

    @Autowired
    CacheHKVService cacheHKVService;

    @Autowired
    OrdersService ordersService;

    @Resource
    private WxpayNativeService wxPayService;

    @Autowired
    AlipayService alipayService;

    /**
     * 查询1800分钟-30分钟前的未支付订单,将其取消处理
     * 每5分钟执行一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void autoCancelOvertimeNoPayPaymentSeq(){
        List<PaymentSeq> paymentSeqs=acClient.overtimeNoPayList();
        if(paymentSeqs!=null && paymentSeqs.size()>0){
            for (PaymentSeq paymentSeq : paymentSeqs) {
                String payKey="overtime-no-pay-payment-seq-"+paymentSeq.getPayId();
                boolean exists=cacheHKVService.setIfAbsent(payKey,"1",60, TimeUnit.MINUTES);
                if(exists){
                    continue;
                }else{
                    try {
                        toHandlePaymentSeq(paymentSeq);
                    }catch (Exception e){
                        log.error("超时未支付订单批量->查询、处理失败",e);
                    }

                }

            }
        }

    }

    /**
     * 先查询第三方支付状态，如果已支付，则走支付确认流程，如果未支付，则把订单设置未取消状态
     * @param paymentSeq
     */
    public void toHandlePaymentSeq(PaymentSeq paymentSeq) throws Exception {
        Orders order = new Orders(paymentSeq.getOrderId());
        order.setOtype(paymentSeq.getOtype());
        order.setId(paymentSeq.getOrderId());
        if("1".equals(paymentSeq.getPayType())){//微信支付
            //去查询微信支付的状态

            String result = wxPayService.queryOrderFromWx(paymentSeq.getOrderId());
            Gson gson = new Gson();
            HashMap plainTextMap = gson.fromJson(result, HashMap.class);
            String tradeState= (String) plainTextMap.get("trade_state");
            //判断订单状态
            if(WxTradeState.SUCCESS.getType().equals(tradeState)){//成功
                log.warn("核实微信订单已支付 ===> {}", order.getId());
                //如果确认订单已支付则更新本地订单状态
                String tranId = (String) plainTextMap.get("transaction_id");
                paymentSeq.setTranId(tranId);

                String amount = String.valueOf(plainTextMap.get("amount"));
                HashMap<String,Object> amountMap = gson.fromJson(amount, HashMap.class);
                String total = String.valueOf(amountMap.get("total"));
                BigDecimal payAt = new BigDecimal(total).divide(new BigDecimal(100));
                paymentSeq.setPayAt(payAt);
                Date date=new Date();
                date.setTime(Long.getLong(String.valueOf(plainTextMap.get("success_time"))));
                paymentSeq.setPayTime(date);
                this.ordersService.payConfirm(paymentSeq.getOtype(), paymentSeq.getOrderId(), paymentSeq.getPayId() , tranId,paymentSeq.getPayAt(),paymentSeq.getRemarks());
            }else{//订单状态未未支付，则取消订单
                log.warn("核实微信订单未支付 ===> {}", order.getId());
                this.ordersService.payCancel(paymentSeq.getOtype(),paymentSeq.getOrderId(),paymentSeq.getPayId(),"订单超时未支付，取消");

            }
        }else if("2".equals(paymentSeq.getPayType())){//支付宝支付
            //去查询支付宝支付的状态
            AlipayTradeQueryResponse response=alipayService.tradeQuery(paymentSeq.getOrderId());
            if("TRADE_SUCCESS".equals(response.getTradeStatus())){//交易成功
                log.warn("核实支付宝订单已支付 ===> {}", order.getId());
                this.ordersService.payConfirm(paymentSeq.getOtype(), paymentSeq.getOrderId(), paymentSeq.getPayId() , response.getTradeNo(),BigDecimal.valueOf(Long.parseLong(response.getPayAmount())),paymentSeq.getRemarks());
            }else{
                log.warn("核实支付宝订单未支付 ===> {}", order.getId());
                this.ordersService.payCancel(order.getOtype(),paymentSeq.getOrderId(),paymentSeq.getPayId(),"订单超时未支付，取消");

            }
        }
    }
}
